package com.irdstudio.efp.esb.api.service.common.repository;

import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.util.Amount2RMB;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.ctr.service.facade.CtrLoanContService;
import com.irdstudio.efp.ctr.service.vo.CtrLoanContVO;
import com.irdstudio.efp.esb.api.bean.psd.apply.req.PsdApproveReqBean;
import com.irdstudio.efp.esb.api.rest.yed.req.YedApproveReqBean;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import com.irdstudio.efp.nls.service.facade.psd.NlsCreditApprovalInfoService;
import com.irdstudio.efp.nls.service.facade.psd.PreNlsCreditInfoService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVOBuilder;
import com.irdstudio.efp.nls.service.vo.psd.NlsCreditApprovalInfoVO;
import com.irdstudio.efp.nls.service.vo.psd.PreNlsCreditInfoVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVOBuilder;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.irdstudio.efp.esb.common.constant.ElectronicSignatureConstant.CONT_STATUS_101;

/**
 * 需求编号:2019D08--
 * 问题编号:
 * 开发人员: caoxin
 * 创建日期:2019/12/3
 * 功能描述:
 * 修改日期:2019/12/3
 * 修改描述:
 */
@Service("nlsRepository")
public class NlsRepository {
    @Autowired
    @Qualifier("nlsApplyInfoService")
    private NlsApplyInfoService nlsApplyInfoService;

    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;

    @Autowired
    @Qualifier("nlsCreditApprovalInfoService")
    private NlsCreditApprovalInfoService nlsCreditApprovalInfoService;

    @Autowired
    @Qualifier("preNlsCreditInfoService")
    private PreNlsCreditInfoService preNlsCreditInfoService;

    @Autowired
    @Qualifier("ctrLoanContService")
    private CtrLoanContService ctrLoanContService;

    private static Logger logger = LoggerFactory.getLogger(NlsRepository.class);

    public NlsApplyInfoVO getNlsApplyInfoBySeq(String applySeq) {
        return nlsApplyInfoService.queryByPk(NlsApplyInfoVOBuilder
                .aNlsApplyInfoVO()
                .withApplySeq(applySeq)
                .build());
    }

    public int getOnWayApply(PsdApproveReqBean psdApplyReqBean) {
        NlsCreditInfoVO nlsCreditInfo = getNlsCreditInfoBySeq(psdApplyReqBean.getCrAppSrlNo());
        return nlsApplyInfoService.countHsdCustHasUsingLetter(
                NlsApplyInfoVOBuilder.aNlsApplyInfoVO()
                        .withCertCode(nlsCreditInfo.getCertCode())
                        .withCertType(nlsCreditInfo.getCertType())
                        .withPrdId(nlsCreditInfo.getPrdId()).build());
    }

    public NlsCreditInfoVO getNlsCreditInfoBySeq(String applySeq) {
        return nlsCreditInfoService.queryByPk(NlsCreditInfoVOBuilder
                .aNlsCreditInfoVO()
                .withLmtApplySeq(applySeq)
                .build());
    }


    public NlsCreditInfoVO getNlsCreditInfoVO(String lmtApplySeq) {
        return getNlsCreditInfoBySeq(lmtApplySeq);

    }

    public List<NlsCreditInfoVO> getNlsCreditInfoCusRecords(String orgCode, String orgId) throws BizException {
        return nlsCreditInfoService.getCusManagerRecord(orgCode, orgId);
    }

    public NlsCreditApprovalInfoVO getNlsCreditInfoApprovalVO(String lmtApplySeq) {
        return nlsCreditApprovalInfoService.selectByPrimaryKey(lmtApplySeq);
    }

    public PreNlsCreditInfoVO getPreNlsCreditInfo(String preLmtApplySeq) {
        PreNlsCreditInfoVO preNlsCreditInfoVO = new PreNlsCreditInfoVO();
        preNlsCreditInfoVO.setApplySeq(preLmtApplySeq);
        return Optional.ofNullable(preNlsCreditInfoService.queryByPk(preNlsCreditInfoVO)).orElse(preNlsCreditInfoVO);
    }

    public void insertLoanCtrContract(NlsApplyInfoVO nlsApplyInfoVO, NlsCreditInfoVO nlsCreditInfoVO, LmtPrdContVO lmtPrdContVO) throws BizException {
        CtrLoanContVO creditCtrLoanContVO = new CtrLoanContVO();
        creditCtrLoanContVO.setContNo(nlsApplyInfoVO.getLmtApplySeq());
        creditCtrLoanContVO = ctrLoanContService.queryByPk(creditCtrLoanContVO);
        //借款合同
        CtrLoanContVO ctrLoanContVO = new CtrLoanContVO();
        //合同编号
        ctrLoanContVO.setContNo(nlsApplyInfoVO.getApplySeq());
        //用信申请流水号
        ctrLoanContVO.setSerno(nlsApplyInfoVO.getApplySeq());
        //用信协议编号
        ctrLoanContVO.setLmtContNo(lmtPrdContVO.getLmtContNo());
        ctrLoanContVO.setPrdCode(nlsApplyInfoVO.getPrdCode());
        ctrLoanContVO.setCusId(nlsApplyInfoVO.getCusId());
        ctrLoanContVO.setChannelCode(nlsApplyInfoVO.getChannelNo());
        ctrLoanContVO.setPrdId(nlsApplyInfoVO.getPrdId());
        ctrLoanContVO.setPrdName(nlsApplyInfoVO.getPrdName());
        ctrLoanContVO.setContAmt(nlsApplyInfoVO.getApplyAmt());
        //合同类型
        ctrLoanContVO.setContType(ConsoleConstant.CONT_TYPE_02);
        //客户名称
        ctrLoanContVO.setCusName(nlsCreditInfoVO.getCusName());
        //证件类型
        ctrLoanContVO.setCertType(nlsCreditInfoVO.getCertType());
        //证件号码
        ctrLoanContVO.setCertCode(nlsCreditInfoVO.getCertCode());
        //期限时间类型
        ctrLoanContVO.setTermTimeType(nlsApplyInfoVO.getLoanTermType());
        //期限
        ctrLoanContVO.setLoanTerm(StringUtil.isNullorBank(nlsApplyInfoVO.getLoanTerm()) ? BigDecimal.ZERO : new BigDecimal(nlsApplyInfoVO.getLoanTerm()));
        //利率浮动比，汇商贷固定利率
        ctrLoanContVO.setCalFloatingRate(BigDecimal.ZERO);
        //还款方式
        ctrLoanContVO.setRepaymentMode(nlsApplyInfoVO.getRepayMethod());
        //合同签订日期
        ctrLoanContVO.setSignDate(nlsApplyInfoVO.getApplyDate());
        //  合同状态
        ctrLoanContVO.setContState(CONT_STATUS_101);
        // 创建时间 创建人
        ctrLoanContVO.setCreateTime(TimeUtil.getCurrentDateTime());
        ctrLoanContVO.setCreateUser("admin");
        ctrLoanContVO.setPerformanceOwner(nlsCreditInfoVO.getNlsOperUserid());
        ctrLoanContVO.setPerformanceOrg(nlsCreditInfoVO.getNlsOperOrgid());
        ctrLoanContVO.setInputId(nlsApplyInfoVO.getCusId());
        ctrLoanContVO.setCusManager(nlsCreditInfoVO.getNlsOperUserid());
        ctrLoanContVO.setInputBrId(nlsCreditInfoVO.getNlsOperOrgid());
        ctrLoanContVO.setMainBrId(nlsCreditInfoVO.getNlsOperOrgid());
        ctrLoanContVO.setFinaBrId(nlsCreditInfoVO.getNlsOperOrgid());
        ctrLoanContVO.setLegalOrgCode(nlsCreditInfoVO.getNlsOperOrgid());
        if (Objects.nonNull(creditCtrLoanContVO)) {
            ctrLoanContVO.setResdntAddr(creditCtrLoanContVO.getResdntAddr());
            ctrLoanContVO.setPstcd(creditCtrLoanContVO.getPstcd());
            ctrLoanContVO.setCtcTelNo(creditCtrLoanContVO.getCtcTelNo());
            ctrLoanContVO.setEmail(creditCtrLoanContVO.getEmail());
        }
        String amount = nlsApplyInfoVO.getApplyAmt().setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        ctrLoanContVO.setLrgLoanAmt(Amount2RMB.convert(amount));
        ctrLoanContVO.setContAmt(nlsApplyInfoVO.getApplyAmt());


        logger.info("************向合同表插入的借款合同为：" + "【" + ctrLoanContVO.toString() + "】");
        int count2 = ctrLoanContService.insertCtrLoanCont(ctrLoanContVO);
        if (count2 == -1) {
            logger.error("普税贷用信通知接口 用信申请流水号:【" + nlsCreditInfoVO.getLmtApplySeq() + "】 插入借款合同异常!");
            throw new BizException(EsbRetCodeStandard.SJCLYC.getValue(), "插入借款合同异常!");
        } else {
            logger.info("************向合同表插入借款合同成功！************");
        }

    }

    public int getOnWayApply(YedApproveReqBean yedApplyReqBean) {
        NlsCreditInfoVO nlsCreditInfo = getNlsCreditInfoBySeq(yedApplyReqBean.getCrAppSrlNo());
        return nlsApplyInfoService.countHsdCustHasUsingLetter(
                NlsApplyInfoVOBuilder.aNlsApplyInfoVO()
                        .withCertCode(nlsCreditInfo.getCertCode())
                        .withCertType(nlsCreditInfo.getCertType())
                        .withPrdId(nlsCreditInfo.getPrdId()).build());
    }
}
